import { create } from 'zustand';
import { XiaohongshuService } from '../services/xiaohongshu';

const xiaohongshuService = new XiaohongshuService();

export interface Account {
  id: string;
  username: string;
  nickname: string;
  phone: string;
  status: 'active' | 'inactive' | 'error';
  followers: number;
  following: number;
  posts: number;
  lastLogin: string;
  cookies?: string;
  token?: string;
  isCurrent?: boolean;
  createdAt: string;
  updatedAt: string;
}

interface AccountStore {
  accounts: Account[];
  currentAccount: Account | null;
  loading: boolean;
  error: string | null;
  
  // 基础操作
  fetchAccounts: () => Promise<void>;
  
  // 新的登录流程
  openLoginPage: () => Promise<{ success: boolean; message: string }>;
  checkLoginStatus: () => Promise<{ isLoggedIn: boolean; message: string }>;
  getLoginInfoAndSave: () => Promise<{ success: boolean; message: string }>;
  
  // 账号管理
  updateAccount: (account: Account) => Promise<void>;
  deleteAccount: (id: string) => Promise<void>;
  syncAccount: (id: string) => Promise<void>;
  switchCurrentAccount: (id: string) => Promise<void>;
  logoutAccount: (id: string) => Promise<void>;
  getCurrentAccount: () => Promise<Account | null>;
}

export const useAccountStore = create<AccountStore>((set, get) => ({
  accounts: [],
  currentAccount: null,
  loading: false,
  error: null,

  fetchAccounts: async () => {
    set({ loading: true, error: null });
    try {
      // 这里应该从Rust后端获取账号列表
      // 暂时使用模拟数据
      const mockAccounts: Account[] = [
        {
          id: '1',
          username: 'test_user',
          nickname: '测试用户',
          phone: '13800138000',
          status: 'active',
          followers: 1250,
          following: 89,
          posts: 45,
          lastLogin: new Date().toISOString(),
          isCurrent: true,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        }
      ];
      const currentAccount = mockAccounts.find(acc => acc.isCurrent) || null;
      set({ accounts: mockAccounts, currentAccount, loading: false });
    } catch (error) {
      set({ error: error instanceof Error ? error.message : '获取账号列表失败', loading: false });
    }
  },

  openLoginPage: async () => {
    try {
      const result = await xiaohongshuService.openLoginPage();
      return result;
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : '打开登录页面失败'
      };
    }
  },

  checkLoginStatus: async () => {
    try {
      const result = await xiaohongshuService.checkLoginStatus();
      return result;
    } catch (error) {
      return {
        isLoggedIn: false,
        message: error instanceof Error ? error.message : '检查登录状态失败'
      };
    }
  },

  getLoginInfoAndSave: async () => {
    try {
      const result = await xiaohongshuService.getLoginInfoAndSave();
      if (result.success && result.account) {
        // 更新本地状态
        const { accounts } = get();
        const existingIndex = accounts.findIndex(acc => acc.id === result.account!.id);

        const newAccount: Account = {
          id: result.account.id,
          username: result.account.username,
          nickname: result.account.nickname,
          phone: result.account.phone,
          status: 'active',
          followers: result.account.followers,
          following: result.account.following,
          posts: result.account.posts,
          lastLogin: result.account.last_login,
          cookies: result.cookies,
          token: result.token,
          isCurrent: true,
          createdAt: result.account.created_at,
          updatedAt: result.account.updated_at,
        };

        let updatedAccounts: Account[];
        if (existingIndex >= 0) {
          updatedAccounts = [...accounts];
          updatedAccounts[existingIndex] = newAccount;
        } else {
          updatedAccounts = [...accounts, newAccount];
        }

        // 将其他账号设为非当前
        updatedAccounts = updatedAccounts.map(acc => ({
          ...acc,
          isCurrent: acc.id === newAccount.id
        }));

        set({
          accounts: updatedAccounts,
          currentAccount: newAccount
        });
      }

      return {
        success: result.success,
        message: result.message
      };
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : '获取登录信息失败'
      };
    }
  },

  updateAccount: async (account: Account) => {
    try {
      const { accounts } = get();
      const updatedAccounts = accounts.map(acc => 
        acc.id === account.id ? account : acc
      );
      set({ accounts: updatedAccounts });
    } catch (error) {
      console.error('更新账号失败:', error);
    }
  },

  deleteAccount: async (id: string) => {
    try {
      const { accounts } = get();
      const updatedAccounts = accounts.filter(acc => acc.id !== id);
      set({ accounts: updatedAccounts });
    } catch (error) {
      console.error('删除账号失败:', error);
    }
  },

  syncAccount: async (id: string) => {
    try {
      const result = await xiaohongshuService.syncData(id);
      if (result.success) {
        // 更新本地账号数据
        const { accounts } = get();
        const updatedAccounts = accounts.map(acc => {
          if (acc.id === id && result.data) {
            return {
              ...acc,
              followers: result.data.followers || acc.followers,
              following: result.data.following || acc.following,
              posts: result.data.posts || acc.posts,
              lastLogin: result.data.last_login || acc.lastLogin,
            };
          }
          return acc;
        });
        set({ accounts: updatedAccounts });
      }
    } catch (error) {
      console.error('同步账号失败:', error);
    }
  },

  switchCurrentAccount: async (id: string) => {
    try {
      const result = await xiaohongshuService.switchAccount(id);
      if (result.success) {
        const { accounts } = get();
        const updatedAccounts = accounts.map(acc => ({
          ...acc,
          isCurrent: acc.id === id
        }));
        const currentAccount = updatedAccounts.find(acc => acc.id === id) || null;
        set({ accounts: updatedAccounts, currentAccount });
      }
    } catch (error) {
      console.error('切换账号失败:', error);
    }
  },

  logoutAccount: async (id: string) => {
    try {
      const { accounts } = get();
      const updatedAccounts = accounts.map(acc => {
        if (acc.id === id) {
          return { ...acc, status: 'inactive' as const };
        }
        return acc;
      });
      set({ accounts: updatedAccounts });
    } catch (error) {
      console.error('退出登录失败:', error);
    }
  },

  getCurrentAccount: async () => {
    try {
      const account = await xiaohongshuService.getCurrentAccount();
      if (account) {
        const convertedAccount: Account = {
          id: account.id,
          username: account.username,
          nickname: account.nickname,
          phone: account.phone,
          status: account.status as 'active' | 'inactive' | 'error',
          followers: account.followers,
          following: account.following,
          posts: account.posts,
          lastLogin: account.last_login,
          cookies: account.cookies,
          token: account.token,
          isCurrent: account.is_current,
          createdAt: account.created_at,
          updatedAt: account.updated_at,
        };
        set({ currentAccount: convertedAccount });
        return convertedAccount;
      }
      return null;
    } catch (error) {
      console.error('获取当前账号失败:', error);
      return null;
    }
  },
})); 